#include "mysqlDataBase.h"
using namespace std;
stdMysqlDataBase::stdMysqlDataBase():m_db(nullptr)
{

}

stdMysqlDataBase::~stdMysqlDataBase()
{

}

bool stdMysqlDataBase::connectDB(const std::string &dbFileName)
{   
    m_db = mysql_init(NULL);

    if(m_db == nullptr)
    {
        cout<<"mysql_init failed."<<endl;
        return false;
    }

    cout<<"初始化数据库成功..."<<endl;

    //连接数据库
    const char * host = "localhost";
    const char * user = "root";
    const char * passwd = "1";
    int port = 3306;
    if(mysql_real_connect(m_db,host,user,passwd,dbFileName.c_str(),port,NULL,0) == NULL)
    {   
        cout<<"file:"<<__FILE__<<"line:"<<__LINE__<<"connect mysql server error:"<<mysql_error(m_db)<<"SUCESS!"<<endl;
        return false;
    }
    cout<<"连接成功"<<endl;
    return true;
}

bool stdMysqlDataBase::execute(const std::string sql)
{   
    int ret = mysql_query(m_db,sql.c_str());
    if(ret != 0)
    {
        cout<<"mysql_query error:"<<mysql_error(m_db)<<endl;
        return false;
    }
    return true;
}

vector<vector<string>> stdMysqlDataBase::query(const std::string sql)
{   
    vector<vector<string>> data;
    int ret = mysql_query(m_db,sql.c_str());
    if(ret != 0)
    {
        cout<<"mysql_query error:"<<mysql_error(m_db)<<endl;
        exit(-1);
    }

    //结果集
    MYSQL_RES * result =  mysql_store_result(m_db);
    if(result == NULL)
    {
        cout<<"mysql_store_result error:"<<mysql_error(m_db)<<endl;
        return data;
    }

    unsigned int cols = mysql_num_fields(result);
    // cout<<"cols:"<<cols<<endl;
    
    // unsigned int rows = mysql_num_rows(result);
    // cout<<"rows:"<<rows<<endl;
    vector<string> rowDate;
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result)) != NULL)
    {
        for(int col = 0;col < cols;col++)
        {
            rowDate.push_back(row[col]);
        }
        data.push_back(rowDate);
    }
    mysql_free_result(result);
    return data;

}

void stdMysqlDataBase::closeDB()
{
    if(m_db != NULL)
    {   
        m_db = NULL;
        mysql_close(m_db);
    }
    
}
